<script setup lang="ts">
import { ref } from "vue";
import EChartsComponent from "@/components/EChartsComponent/index.vue";
import { computed, onMounted, reactive, onBeforeUnmount } from "vue";
import { getDataBySQLDesc } from "@/api/common";
import dayjs from "dayjs";
import { usePieChartOption, useBarChartOption } from "./chartOptions";

defineOptions({
  name: "Outbound"
});
const REFRESH_INTERVAL = 10 * 60 * 1000; // 10分钟刷新一次

// 数字展示配置
const createDigitalFlopConfig = () => ({
  number: [0],
  toFixed: 0,
  textAlign: "center",
  content: "{nt}",
  style: {
    fontSize: 26
  }
});

const config1 = ref(createDigitalFlopConfig());
const config2 = ref(createDigitalFlopConfig());

// 图表配置
const { option } = usePieChartOption();
const { option2 } = useBarChartOption();

const currentTime = ref("");
const config = ref({
  header: [
    "订单号",
    "订单客户",
    "跟单",
    "物流/快递",
    "灯具/模组数量",
    "备货数量"
  ],
  data: [],
  headerHeight: 50,
  index: false,
  columnWidth: [200, 200, 80, 150, 180, 100],
  align: "center",
  headerBGC: "#f0f2f5",
  oddRowBGC: "#fff",
  evenRowBGC: "#fff",
  rowNum: 10,
  bodyStyle: {
    fontSize: 14,
    color: "#000" // 表体字体颜色修改为黑色
  }
});
const data3 = ref({
  time: "",
  NotBatch: "",
  AllBatch: ""
});

// 定时器管理
let refreshInterval: number | null = null;
let intervalId: number | null = null;
let serverTime: dayjs.Dayjs | null = null;
let localTimestamp = 0;

// 获取服务器时间
const getTimeNow = async (): Promise<void> => {
  const params = { action: "public/get_server_sysdate" };
  const { data } = await getDataBySQLDesc(params);
  const dateStr = data[0].日期时间;

  localTimestamp = Date.now();
  serverTime = dayjs(dateStr, "YYYY-MM-DD HH:mm:ss");
};

// 开始计时器
const startTimer = (): void => {
  if (intervalId) clearInterval(intervalId);

  const update = (): void => {
    if (!serverTime) return;

    const elapsed = Date.now() - localTimestamp;
    const currentServerTime = serverTime.add(elapsed, "millisecond");
    currentTime.value = currentServerTime.format("YYYY-MM-DD dddd HH:mm:ss");
  };

  update(); // 立即执行一次
  intervalId = window.setInterval(update, 1000);
};

// 清除计时器
onBeforeUnmount(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
});

// 获取表格数据
const getTableData = async (params: any): Promise<void> => {
  const { data } = await getDataBySQLDesc(params);

  const fieldsToExtract = [
    "订单单号",
    "跟单",
    "出通物流",
    "申请出通数量",
    "备货数量"
  ];

  config.value.data = data.map(item =>
    fieldsToExtract.map(field => item[field] || "")
  );
};

// 获取饼图数据
const getChartsData3 = async (params: any): Promise<void> => {
  const { data } = await getDataBySQLDesc(params);

  data3.value.time = dayjs(data[0].日期).format("YYYY-MM-DD") || "";
  data3.value.NotBatch = data[0].今日已发 || 0;
  data3.value.AllBatch = data[0].今日应发 || 0;

  const newNumber = Number(data[0]?.今日已发) || 0;
  const newNumber1 = Number(data[0]?.今日应发) || 0;

  config1.value.number = [newNumber];
  config2.value.number = [newNumber1];

  const num = Number(data[0].发货率) * 100 || 0;
  option.value.title.text = "{a|发货率}\n{b| " + num + " %}";
  option.value.series[0].data = [num];
};

// 获取柱状图数据
const getChartsData2 = async (params: any): Promise<void> => {
  const { data } = await getDataBySQLDesc(params);

  option2.value.series[0].data = [];
  option2.value.xAxis[0].data = [];

  data.forEach(item => {
    option2.value.series[0].data.push({
      name: item.发货日期,
      value: item.发货批次
    });
    const formattedDate = dayjs(item.发货日期).format("YYYY-MM-DD");
    option2.value.xAxis[0].data.push(formattedDate);
  });
};

// 获取参数的通用函数
const fetchParams = async (hsmc: string): Promise<Record<string, string[]>> => {
  const params = { action: "public/get_bi_sjfw", hsmc };
  const { data } = await getDataBySQLDesc(params);

  return data.reduce((acc, item) => {
    acc[item["参数编码"]] = item["参数值"];
    return acc;
  }, {});
};

// 自动刷新数据
const startAutoRefresh = (): void => {
  if (refreshInterval) clearInterval(refreshInterval);

  const fetchAllData = async (): Promise<void> => {
    // 获取参数并加载数据
    const [result, result1, result2, result3] = await Promise.all([
      //下面2个是滚屏参数
      fetchParams("get_ckfhkb_jrwfhmx"),
      fetchParams("get_ckfhkb_jrwfhmx_bhmx"),
      //块状图参数and饼图
      fetchParams("get_ckfhkb_jrfhfx"),

      //柱状图参数
      fetchParams("get_ckfhkb_mrfhfx")
    ]);

    // 加载滚屏数据
    const params = {
      action: "biz/reports/get_ckfhkb_jrwfhmx_bhmx",
      ...result,
      ...result1
    };
    getTableData(params);

    // 加载饼图数据
    const params1 = {
      action: "biz/reports/get_ckfhkb_jrfhfx",
      ...result2
    };
    getChartsData3(params1);

    // 加载柱状图数据
    const params2 = {
      action: "biz/reports/get_ckfhkb_mrfhfx",
      ...result3
    };
    getChartsData2(params2);
  };

  // 立即执行一次
  fetchAllData();

  // 设置定时刷新
  refreshInterval = window.setInterval(fetchAllData, REFRESH_INTERVAL);
};

onMounted(async () => {
  // 获取服务器时间并启动计时器
  await getTimeNow();
  startTimer();
  // 启动自动刷新
  startAutoRefresh();
});
</script>

<template>
  <div class="flex flex-col arrived">
    <h1 class="text-center text-2xl font-bold mb-4 text-gray-800">发货监控</h1>
    <div class="flex flex-row arrived-content">
      <div class="w-full">
        <dv-scroll-board class="scrollBoard" :config="config" />
      </div>
      <!--      <div class="w-2/5">-->
      <!--        <h3>{{ data3.time }}</h3>-->
      <!--        <div class="batchBox">-->
      <!--          <div class="batchItem">-->
      <!--            <div class="batchName">今日未发货</div>-->
      <!--            <div class="batchNum batchNum1">{{ data3.NotBatch }}</div>-->
      <!--          </div>-->
      <!--          <div class="batchItem">-->
      <!--            <div class="batchName">今日应发</div>-->
      <!--            <div class="batchNum">{{ data3.AllBatch }}</div>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--        <div class="chart chart1">-->
      <!--          <EChartsComponent :extraOptions="option" type="pie" />-->
      <!--        </div>-->
      <!--        <div class="chart">-->
      <!--          <EChartsComponent :extraOptions="option2" type="bar" />-->
      <!--        </div>-->
      <!--      </div>-->
    </div>
  </div>
</template>
<style lang="scss" scoped>
.main-content.arrived {
  margin: 0;
  height: 100%;
  padding: 20px;
}

.dv-scroll-board {
  color: #000; // 表体字体颜色修改为黑色;
}

.chart {
  height: calc(40% - 0.5rem);
  background: #fff;
  border-radius: 0.5rem;
  margin: 0 1rem;
}

.chart1 {
  margin-bottom: 1rem;
}

.arrived-content {
  height: calc(100% - 32px);
}

.scrollBoard {
  height: 100%;
  background: #fff !important;
}

// .dv-scroll-board .rows {
//   background: #fff !important;
// }

h3 {
  height: 50px;
  display: flex;
  justify-content: center;
}

.batchBox {
  height: calc(20% - 50px);
  display: flex;
  justify-content: space-between;
  padding: 0 1rem;
  box-sizing: border-box;
}

.batchItem {
  height: calc(100% - 1rem);
  width: calc(50% - 0.5rem);
  background: #fff;
  border-radius: 0.5rem;
  // background: rgba(0, 93, 207, 0.2);
}

.batchName {
  height: 3rem;
  line-height: 3rem;
  font-size: 1.2rem;

  text-align: center;
}

.batchNum {
  height: calc(100% - 3rem);
  font-size: 2.5rem;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #005dcf;
}

.batchNum1 {
  color: #999;
}
</style>
